import { NextResponse } from 'next/server';
import { AppDataSource } from '@/database';
import { Todo } from '@/entities/Todo';

// 初始化数据库连接
const initializeDB = async () => {
  if (!AppDataSource.isInitialized) {
    await AppDataSource.initialize();
  }
};

// PATCH /api/todos/[id]
export async function PATCH(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    await initializeDB();
    const todoRepository = AppDataSource.getRepository(Todo);
    const todo = await todoRepository.findOne({ where: { id: params.id } });

    if (!todo) {
      return NextResponse.json(
        { error: 'Todo not found' },
        { status: 404 }
      );
    }

    // 更新完成状态和更新时间
    todo.completed = !todo.completed;
    todo.updatedAt = new Date();
    
    const updatedTodo = await todoRepository.save(todo);
    return NextResponse.json(updatedTodo);
  } catch (error) {
    console.error('Error updating todo:', error);
    return NextResponse.json(
      { error: 'Failed to update todo' },
      { status: 500 }
    );
  }
}

// DELETE /api/todos/[id]
export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    await initializeDB();
    const todoRepository = AppDataSource.getRepository(Todo);
    const result = await todoRepository.delete(params.id);

    if (result.affected === 0) {
      return NextResponse.json(
        { error: 'Todo not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting todo:', error);
    return NextResponse.json(
      { error: 'Failed to delete todo' },
      { status: 500 }
    );
  }
} 